import { Card, List, Image } from 'antd';
import React, { useEffect } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import ProList from '@ant-design/pro-list';
import styles from '@/pages/collection/MyCollectionList/index.less';
import CreateCollection from './components/CreateCollection';
import { connect, Link } from 'umi';

const MyCollectionList = (props) => {
  const { dispatch, status, collectionList, currentUser, collectionListLoading } = props;

  useEffect(() => {
    if (collectionListLoading) {
      return;
    }

    dispatch({
      type: 'myCollectionList/searchCollectionList',
      payload: { userID: currentUser.id },
    });
  }, [status]);

  const onFinish = (values) => {
    const formData = new FormData();
    formData.append('name', values.name);
    formData.append('description', values.description);
    formData.append('logo', values.logo[0].originFileObj);
    formData.append('userID', currentUser.id);
    dispatch({
      type: 'myCollectionList/addCollection',
      payload: formData,
    });
    return true;
  };

  const content = (
    <div className={styles.pageHeaderContent}>
      <p>创建收藏（您自己的店面），上传数字创作，并出售。</p>
    </div>
  );

  const nullData = {};

  return (
    <PageContainer content={content}>
      <ProList
        rowKey="id"
        loading={collectionListLoading}
        grid={{
          gutter: 16,
          xs: 1,
          sm: 2,
          md: 3,
          lg: 3,
          xl: 4,
          xxl: 4,
        }}
        dataSource={[nullData, ...collectionList]}
        renderItem={(item) => {
          if (item && item.id) {
            return (
              <List.Item key={item.id}>
                <Link to={`/trade/myCollection/${item.id}`}>
                  <Card
                    hoverable
                    cover={
                      <Image
                        height={220}
                        alt="logo"
                        preview={false}
                        src={`/api/getLogo/?fileHash=${item.logo}`}
                        fallback=""
                        fallback=""
                      />
                    }
                  >
                    <Card.Meta title={item.name} />
                  </Card>
                </Link>
              </List.Item>
            );
          }

          return (
            <List.Item>
              <CreateCollection onFinish={onFinish} />
            </List.Item>
          );
        }}
      />
    </PageContainer>
  );
};

export default connect(({ myCollectionList, user, loading }) => ({
  status: myCollectionList.status,
  collectionList: myCollectionList.collectionList,
  currentUser: user.currentUser,
  collectionListLoading: loading.effects['myCollectionList/searchCollectionList'],
}))(MyCollectionList);
